package ev.selection;//need to add this line

import java.util.*;

import TeamPursuit.MensTeamPursuit;
import TeamPursuit.SimulationResult;
import TeamPursuit.WomensTeamPursuit;

import ev.initial.Individual;

public class NewSimpleSelection implements Selection{

	public ArrayList<Individual> select(ArrayList<Individual> oldPopulation, int limit)
	{
		Random r=new Random();
		int size=oldPopulation.size();
		if(size<limit){
			//System.exit(0);
			System.out.println("error: limit can not be larger than population size");
		}
		Collections.sort(oldPopulation);
		ArrayList<Individual> newPopulation=new ArrayList<Individual>();
		for(int i=0; i<3; i++){
			newPopulation.add(oldPopulation.get(i));
		}
		for(int i=3; i<limit-1; i++){
			newPopulation.add(oldPopulation.get(r.nextInt(size-3)+3));
		}
		
		//add one new individual for each selection
		SimulationResult result = null;
        //WomensTeamPursuit womensTeamPursuit = new WomensTeamPursuit();
		MensTeamPursuit mensTeamPursuit = new MensTeamPursuit();
		try {
			
			mensTeamPursuit.setHeight(0, 1.80);
			mensTeamPursuit.setWeight(0, 80.0);
			mensTeamPursuit.setMeanMaximumPower(0, 6.5);
			
			mensTeamPursuit.setHeight(2, 1.70);
			mensTeamPursuit.setWeight(2, 70.0);
			mensTeamPursuit.setMeanMaximumPower(2, 5.5);
			
			mensTeamPursuit.setHeight(3, 1.80);
			mensTeamPursuit.setWeight(3, 80.0);
			mensTeamPursuit.setMeanMaximumPower(3, 5.5);
			
			//result = mensTeamPursuit.simulate(DEFAULT_MENS_TRANSITION_STRATEGY, DEFAULT_MENS_PACING_STRATEGY);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		int sLength=oldPopulation.get(0).getStrategy().length;
		int pLength=oldPopulation.get(0).getPacing().length;
		boolean [] strategy3 = new boolean[sLength];
		for(int i=0;i<sLength;i++){
			strategy3[i] = r.nextBoolean();
			if(i>1&&strategy3[i]==strategy3[i-1]&&strategy3[i]==strategy3[i-2]){
				if(strategy3[i]){
					strategy3[i]=false;
				}else{
					strategy3[i]=true;
				}
			}
		}

		int [] power3 = new int[pLength];
	    for(int i=0;i<pLength;i++){
			power3[i] = r.nextInt(1001)+200;
		}
	    try {
			result=mensTeamPursuit.simulate(strategy3, power3);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		while(!isValid(result)){
			for(int i=0;i<sLength;i++){
				strategy3[i] = r.nextBoolean();
			}
			for(int i=0;i<pLength;i++){
				power3[i] = r.nextInt(601)+200;
			}
			try {
				result=mensTeamPursuit.simulate(strategy3, power3);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("add new individual for each selection");
		Individual indiv3=new Individual(strategy3,power3);
		indiv3.setTime(result.getFinishTime());
		newPopulation.add(indiv3);
		
		return newPopulation;
	}
	private boolean isValid(SimulationResult result){
		if(result.getProportionCompleted() < 0.9999998){
			return false;
		}else{
			return true;
		}
	}
}
